# -*- coding: utf-8 -*-
from src.com.ydzy.util.file_util import FileClient
from src.com.ydzy.util.sql_util import MySQLUtils

db = MySQLUtils('192.168.9.73', 33064, 'root', 'root', 'audit_dev')
file_client=FileClient()


def get_tables(remove_tables=[]):
    sql="show tables;"
    tables_names_of_database=db.retrieve_sql(sql)
    tables_names_of_database=[item[0] for item in tables_names_of_database if item[0] not in remove_tables]
    return tables_names_of_database


def get_all_createTable_sql(table):
    dict={}
    sql=f"SHOW CREATE TABLE {table};"
    createTable_sql = db.retrieve_sql(sql)[0]
    dict[createTable_sql[0]] = createTable_sql[1]
    return dict

def get_all_createTable_sqls():
    sqls=[]
    remove_tables = ['test']
    tables_names_of_database = get_tables(remove_tables)
    for item in tables_names_of_database:
        sql_dict=get_all_createTable_sql(item)
        sqls.append(sql_dict)
    return sqls


def modify_sql2_doris(k, v):
    v=v.replace("CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci","")
    v=v.replace("DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC","")
    v=v.replace("ENGINE=InnoDB AUTO","ENGINE=OLAP")

    commit=str(v[v.index("COMMENT="):])
    commit=commit.split("=")[1].replace("'","")
    return v,commit


def main():
    create_sqls=[]
    sql_dicts = get_all_createTable_sqls()
    for sql_dict in sql_dicts:
        for k,v in sql_dict.items():
            sql,commit=modify_sql2_doris(k,v)
            create_sqls.append("-- "+commit+"\n"+sql)
        break

    write_sql="\n\n\n".join(create_sqls)
    print(write_sql)
    file_client.write(".\doris.txt",write_sql)


if __name__ == "__main__":
    main()